import { useEffect, useState } from "react"
import { contractChildervice } from "../services";
import { message } from "antd";

/**
 * 处理合同列表异步加载数据
 * @param dataRows 接口返回合同数据
 * @param dataSourceTable 处理后合同数据
 * @param setDataSourceTable 保存处理后的合同数据
 * @param tableExpantKeys 合同展开行的key
 * @param setTableExpantKeys 保存合同展开行的key
 * @returns 
 */
export const useDataSourceTable = (
  dataRows: Record<string, any>[],
  dataSourceTable: Record<string, any>[],
  setDataSourceTable: (rows: Record<string, any>[]) => void,
  tableExpantKeys: string[],
  setTableExpantKeys: (keys: string[]) => void
) => {

  /** 保存展开的key */
  const [tableExpandKey, setTableExpandKey] = useState<string>("")

  /** 处理子合同 */
  const asyncChildData = (pKey: string, childList: Record<string, any>[] | any) => {
    let dataList: Record<string, any>[] = []
    dataSourceTable?.forEach((item: any) => {
      dataList?.push({
        ...item,
        children: item?.id == pKey ? childList : item?.children
      })
    })
    setDataSourceTable(dataList)
  }

  /** 处理展开的表格key值 */
  const handleTableExpant = (open: boolean, clickKey: string) => {
    let openKeys: string[] = [...tableExpantKeys]
    if (open) {
      openKeys?.push(clickKey)
    } else {
      openKeys = tableExpantKeys?.filter((item: any) => item != clickKey)
    }
    setTableExpantKeys(openKeys)
  }

  /** 获取变更或解除合同个数回调 */
  const childManageCallback = (res: any) => {
    if (res && res?.msgFlag) {
      handleTableExpant(true, tableExpandKey)
      asyncChildData(tableExpandKey, res?.obj)
    } else {
      message.error(res?.msg)
    }
  }

  /**  获取管理页数据 */
  const { loading, getChildManage } = contractChildervice(childManageCallback);

  /** 初始化数据 */
  useEffect(() => {
    let dataList: Record<string, any>[] = []
    if (dataRows?.length > 0) {
      dataRows?.forEach((item: any) => {
        dataList?.push({
          ...item,
          children: item?.relateNum && item?.relateNum > 0 ? [] : null
        })
      })
    }
    setDataSourceTable(dataList)
    setTableExpantKeys([])
  }, [dataRows])

  /**处理展开关闭数据事件 */
  const onExpandTable = (expanded: boolean, record: Record<string, any>) => {
    if (expanded) {
      setTableExpandKey(record?.id)
      getChildManage({
        pID: record?.id
      })
    } else {
      asyncChildData(record?.id, [])
      handleTableExpant(false, record?.id)
    }
  }

  return {
    onExpandTable,
    childLoading: loading,
  }
}